//
//  HomeVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/19.
//

import UIKit
import SwiftQRScanner


class HomeVC: BaseVC,QRScannerCodeDelegate {

    var conversations = [DMCCConversation]()
    var count = Int()
    var serverNotCount = Int()
    var lock = NSLock()
    var scanner = QRCodeScannerController()

    // 创建局部并发队列
    let msgQueue = DispatchQueue(label: "HomeQueue", attributes: .concurrent)
    
    lazy var addView: HomePopView = {
        addView = HomePopView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
        addView.addViewBlock = { [weak self] index in
            guard let self = self else { return }
            self.popViewAction(index: index)
        }
        return addView
    }()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        
        updateBadgeNumber()
        msgQueue.async() {
            self.getReloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        NSNotification.Name(rawValue: OsnEventType.ReceiveMessages.rawValue)
        // 添加观察者以监听消息接收事件
//        NotificationCenter.default.addObserver(self, selector: #selector(onReceiveMessages), name: NSNotification.Name(rawValue: OsnEvent.ReceiveMessages.rawValue), object: nil)
        geventService.addObserver(OsnEvent.ReceiveMessages, "ReceiveMessages_HomeVC") { [self] data in
            let msg = data as? DMCCMessage
            onReceiveMessages(msg: msg!)
        }
        
        geventService.addObserver(OsnEvent.FriendListUpdated, "FriendListUpdated_HomeVC") { [self] data in
            onFriendListUpdatedMessages()
        }
        
        geventService.addObserver(OsnEvent.RecallMessages, "RecallMessages_HomeVC") { [self] data in
            conversationListMessages()
        }
        
        geventService.addObserver(OsnEvent.kUpDateConversation, "kUpDateConversation_HomeVC") { [self] data in
            conversationListMessages()
        }

        NotificationCenter.default.addObserver(self,
                                               selector: #selector(conversationListMessages),
                                               name: NSNotification.Name(rawValue: kUpdateConversation),
                                               object: nil)
        setup()
        
        self.requestData()
    }
    
    
    
    @objc func requestData() {
        

        // 使用 dispatch_sync 来保证线程安全
        DispatchQueue.global().sync {
//            // 使用 _lock 来锁定临界区
            self.conversations = gosnConversation.getConversationList(sorted: true)//DMCCIMService.getInstance()!.getConversationWithLine([0, 1, 2], line: -1)
        }

        
        
        GK_main_async_safe {
            self.tableView.mj_header!.endRefreshing()
            self.sortData()
            
            if self.conversations.isEmpty {
                self.view.insertSubview(self.nullView, aboveSubview: self.tableView)
            } else {
                self.nullView.removeFromSuperview()
            }
            self.tableView.reloadData()
        }
        
    }
    
    // 刷新会话列表
    func reloadConversationList(_ list: [String]) {
        var conversations = [DMCCConversation]()
        
        for target in list {
            if let conv = getConversationFromList(target) {
                let newConv = gosnConversation.getConversationInfo(target)   //.getConversation(target)
                freshConversation(newConv: newConv!, old: conv)
                
                DispatchQueue.main.async { [self] in
                    self.lock.lock()
                    defer { self.lock.unlock() }
                    if let index = conversationIndexOf(target: target) {
                        let indexPath = IndexPath(row: index, section: 0)
                        let indexPaths = [indexPath]
                        self.tableView.reloadRows(at: indexPaths, with: .none)
                    }
                }
                conversations.append(conv)
            } else {
                var conv = gosnConversation.getConversationInfo(target)
                if conv == nil {
                    conv = gosnConversation.initParam(target)
                    if gosnConversation.setConversationInfo(conv!) {
                        
                    }
                }
//                let conv = gosnConversation.getConversationInfo(target) ?? gosnConversation.setConversationInfo() //.insertConversation(target)
                if conv != nil {
                    getData()
                }
            }
        }
        
        if !conversations.isEmpty {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [self] in
                insertConversationsTop(list: conversations)
            }
        }
    }

    // 在顶部插入会话
    func insertConversationsTop( list: [DMCCConversation]) {
        var needsReload = false
        for info in list {
            guard let index = conversationIndexOf(target: info.targetId) else {return}
               let realIndex = getRealIndex(target: info.targetId)
            if index == realIndex {
                return
            }
            if index != realIndex {
                needsReload = true
                lock.lock()
                defer { lock.unlock() }
                conversations.remove(at: index)
                conversations.insert(info, at: realIndex)
            }
            
        }
        
        if needsReload {
            DispatchQueue.main.async { [self] in
                lock.lock()
                defer { lock.unlock() }
                self.tableView.reloadData()
            }
        }
    }

    // 检查数组是否包含指定字符串
    func stringListContains(_ list: [String], target: String) -> Bool {
        return list.contains { $0 == target }
    }

    // 刷新旧数据
    func reloadOldData(message: DMCCMessage) {
        if let conv = getConversationFromList(message.target) {
            let newConv = gosnConversation.getConversationInfo(message.target)
            freshConversation(newConv: newConv!, old: conv)
            
            lock.lock()
            defer { lock.unlock() }
            DispatchQueue.main.async { [self] in
                if let index = conversationIndexOf(target: conv.targetId) {
                    let indexPath = IndexPath(row: index, section: 0)
                    let cell = self.tableView.cellForRow(at: indexPath)
                    if cell != nil {
                        self.tableView.reloadRows(at: [indexPath], with: .none)
                    } else {
                        self.tableView.reloadData()
                    }
                }
            }
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [self] in
                insertTopConversation(info: conv)
            }
        } else {
            let conv = gosnConversation.getConversationInfo(message.target)
//            gosnConversation.getConversationInfoFrom(message)
            if gosnConversation.setConversationInfo(conv!) {
                
            }
            if conv != nil {
                cancelGetData()
            }
        }
    }

    // 刷新通知
    func reloadNotice(_ message: DMCCMessage) {
//        if let conv = getNoticeConversation() {
////            let newConv = gosnConversation.getConversationInfo("notice")
//            let newConv = gosnConversation.getConversationInfo("notice")
//            freshConversation(newConv: newConv!, old: conv)
//            
//            lock.lock()
//            defer { lock.unlock() }
//            DispatchQueue.main.async { [self] in
//                if let index = conversationIndexOf(target: conv.targetId) {
//                    let indexPath = IndexPath(row: index, section: 0)
//                    let cell = self.tableView.cellForRow(at: indexPath)
//                    if cell != nil {
//                        self.tableView.reloadRows(at: [indexPath], with: .none)
//                    } else {
//                        self.tableView.reloadData()
//                    }
//                }
//                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [self] in
//                    insertTopConversation(info: conv)
//                }
//            }
//        } else {
//            let conv = gosnConversation.getConversationInfo("notice")
//            if conv != nil {
                cancelGetData()
//            }
//        }
    }

    // 获取通知会话
    func getNoticeConversation() -> DMCCConversation? {
        return conversations.first(where: { $0.type.rawValue == 3})
    }

    // 刷新会话信息
    func freshConversation(newConv: DMCCConversation, old: DMCCConversation) {
        old.lastMessage = newConv.lastMessage
        old.timestamp = newConv.timestamp
        old.isTop = newConv.isTop
        old.isSilent = newConv.isSilent
        old.unread = newConv.unread
        old.unreadMention = newConv.unreadMention
        old.unreadMentionAll = newConv.unreadMentionAll
        old.newestMessage = newConv.newestMessage
    }

    // 从列表获取会话
    func getConversationFromList(_ target: String) -> DMCCConversation? {
        return conversations.first(where: { $0.targetId == target })
    }

    // 插入顶部会话
    func insertTopConversation(info: DMCCConversation) {
        guard let index = conversationIndexOf(target: info.targetId) else { return}
        let realIndex = getRealIndex(target: info.targetId)
        if realIndex == index {
            return
        }
        if index != realIndex {
            DispatchQueue.main.async { [self] in
                if index != -1 {
                    if index != realIndex {
                        lock.lock()
                        defer { lock.unlock() }
                        conversations.remove(at: index)
                        conversations.insert(info, at: realIndex)
                        tableView.reloadData()
                    }
                }
            }
        }
        
    }

    // 获取顶部数据索引
    func getTopDataIndex() -> Int {
        return conversations.filter({ $0.isTop }).count
    }

    // 获取消息下标，用来局部刷新
    func conversationIndexOf(target: String) -> Int? {
        guard !conversations.isEmpty else {
            cancelGetData()
            return -1
        }
        return conversations.firstIndex(where: { $0.targetId == target })
    }

    // 取消获取数据
    func cancelGetData() {
        print("[cancelGetData]")
//        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(requestData), object: nil)
////        cancelPreviousPerformRequests(withTarget: self, selector: #selector(getData), object: nil)
//        perform(#selector(requestData), with: nil, afterDelay: 2)
        self.requestData()
    }

    // 顶部数据源
    func topDataSource() {
        var topUnread = [DMCCConversation]()
        var normalUnread = [DMCCConversation]()
        

        let tempArr = Array(conversations)
        
        for conv in tempArr {
            if conv.isTop {
                topUnread.append(conv )
            } else {
                normalUnread.append(conv )
            }
        }
        
        topUnread = sortConversationWithTime(topUnread)
        normalUnread = sortConversationWithTime(normalUnread)
        topUnread.append(contentsOf: normalUnread)
        

        conversations.removeAll()
        conversations.append(contentsOf: topUnread)
    }

    // 获取实际索引
    func getRealIndex(target: String) -> Int {
        var topUnread = [DMCCConversation]()
        var normalUnread = [DMCCConversation]()
        
        topUnread = Array(conversations)
        
        for conv in topUnread {
            if conv.isTop {
                topUnread.append(conv)
            } else {
                normalUnread.append(conv)
            }
        }
        
        topUnread = sortConversationWithTime(topUnread)
        normalUnread = sortConversationWithTime(normalUnread)
        topUnread += normalUnread
        
        for (index, conv) in topUnread.enumerated() {
            if conv.targetId == target {
                return index
            }
        }
        
        return -1
    }

    // 根据时间排序会话
    func sortConversationWithTime(_ conversations: [DMCCConversation]) -> [DMCCConversation] {
        // 实现排序逻辑
        return conversations.sorted(by: { $0.timestamp > $1.timestamp })
    }
    
    // 刷新数据
    func getReloadData() {
        guard !conversations.isEmpty else { return }
        
        for oldConv in self.conversations {
            if let newConv = gosnConversation.getConversationInfo(oldConv.targetId) {
                self.freshConversation(newConv: newConv, old: oldConv)
            }
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.sortData()
        }
    }

    // 排序数据
    func sortData() {
        DispatchQueue.global().async {
            self.topDataSource()
            GK_main_async_safe {
                self.tableView.reloadData()
            }
        }
    }

    // 获取用户信息
    func getUserInfo(_ conv: DMCCConversation) -> DMCCUser? {
        return gosnUser.getUserInfoDefault(conv.targetId)
//        osnUser.getUserInfo(conv.targetId)
    }

    // 获取群组信息
    func getGroupInfo(_ conv: DMCCConversation) -> DMCCGroup? {
        return gosnGroup.getGroupInfoDefault(conv.targetId)
    }
    
    func popViewAction (index:Int) {
        switch index {
        case 0:
            let scanner = QRCodeScannerController()
            scanner.title = "扫一扫"
            scanner.delegate = self
            self.scanner = scanner
            self.present(scanner, animated: true, completion: nil)
            break
            
        case 1:
            let vc = CreateGroupVC() //创建群聊
            vc.blockStr = { [weak self] groupId in
                guard let self = self else { return }
                let con = gosnConversation.initParam(groupId)
                self.navigationController?.pushViewController(ChatVC(conversation: con), animated: true)
            }
            vc.modalPresentationStyle = .overFullScreen
            self.present(vc, animated: true, completion: nil)
            break
        case 2:
//            self.presentVC(VC: CreateGroupVC())
            self.navigationController?.pushViewController(SearchOsnIdVC(), animated: true)
            break

        default:
            break
        }
    }


    // 删除会话
    func deleteChat(_ index: Int) {
        
        
        let str = "确定删除并清空记录?"
        MHAlert.showCustomAlert(str) { [self] ac in
            if ac.title == "Sure".localized() {

                let info = conversations[index]
                if  gosnConversation.deleteConversation(info.targetId) {
                   _ = gosnMessage.clearMessage(info.targetId)
                    cancelGetData()
                    updateBadgeNumber()
                }
            }
        }
    }

    // 不显示
    func clearChat(_ index: Int) {
        
        let con = conversations[index]
        if  gosnConversation.deleteConversation(con.targetId) {
//                    gosnConversation.clearConversation(con.targetId)
            cancelGetData()
            updateBadgeNumber()
        }
        
        
        
    }

    // 置顶消息
    func topChat(_ index: Int, isTop: Bool) {
        let info = conversations[index]
        cancelGetData()
        info.isTop = isTop
        gosnConversation.setTop(info.targetId, isTop)
        cancelGetData()
        
    }
    
    func codeAction(code:String){
        
        let urlPrefixes = ["ospn://user", "ospn://group", "ospn://pcsession", "ospn://weblogin"]
        for prefix in urlPrefixes {
            if let range = code.range(of: prefix, options: .caseInsensitive), range.lowerBound == code.startIndex {
                switch prefix {
                case "ospn://user":
                    handleUserPrefix(code)
                case "ospn://group":
                    handleGroupPrefix(code)
                case "ospn://pcsession":
                    // Handle PC session prefix
                    break
                case "ospn://weblogin":
                    handleWebLoginPrefix(code)
                default:
                    break
                }
                return
            }
        }
    }
    
    private func handleUserPrefix(_ str: String) {
//        MHAlert.showLoading()
        let range = str.range(of: "ospn://user/") ?? str.startIndex..<str.endIndex
        let scanStr = String(str[range.upperBound...])
        let userInfo = gosnUser.getUserInfoDefault(scanStr) // Assuming this is the correct initializer
        if gosnFriend.isFriend(userInfo.userId){ //.isMyFriend(userInfo.userId) {
            let vc = UserDetailVC(userInfo: userInfo)
            navigationController?.pushViewController(vc, animated: true)
        } else {
            let vc = AddUserVC(userInfo: userInfo)
            navigationController?.pushViewController(vc, animated: true)
        }
    }

    private func handleGroupPrefix(_ str: String) {
        let range = str.range(of: "ospn://group/") ?? str.startIndex..<str.endIndex
        let scanStr = String(str[range.upperBound...])
        
        let groupId = scanStr
        let convInfo = gosnConversation.getConversationInfo(groupId)
        
        if convInfo != nil {
            let vc = ChatVC(conversation: convInfo!)
            navigationController?.pushViewController(vc, animated: true)
        } else {
            let groupInfo = gosnGroup.getGroupInfoDefault(groupId) // Assuming this is the correct initializer
            let vc = AddGroupVC(group: groupInfo)
            navigationController?.pushViewController(vc, animated: true)
        }
    }

    private func handleWebLoginPrefix(_ str: String) {
        let range = str.range(of: "ospn://weblogin/") ?? str.startIndex..<str.endIndex
        let scanStr = String(str[range.upperBound...])
        
        
        let url = gosnLogin.loginWithGetWebUrl(scanStr)
//        let dic = OsnUtils.toJson(scanStr)//json2Dics(scanStr) ?? [:]
//        var mutableDic = dic
//        let timestamp = OsnUtils.getTimeStamp()
//        mutableDic?["timestamp"] = timestamp
//        let calc = "\(dic?["url"] ?? "")\((dic!["webId"] ?? ""))\(timestamp)"
//        let hash = EcUtils.osnHash(data: calc.data(using: .utf8)!)//.hashData(calc.data(using: .utf8)!)
//        let sign = EcUtils.osnSign(priKey: gimService.mOsnKey, data: hash.data(using: .utf8)!)//.sign(hash!.data(using: .utf8)!)
//        mutableDic!["sign"] = sign
//        mutableDic["osnId"] = DMCCIMService.getInstance().getUserID
//        let url = dic?["url"] as! String
        let alertMessage = KLocalizedString("ScanloginTitle") + url
        
//        String(format: KLocalizedString("ScanloginTitle"), dic["url"] ?? "")
        MHAlert.showCustomAlert(str) { ac in
            if ac.title == KLocalizedString("Sure") {
                MHAlert.showLoading()
//                MHHYAPIManager.instanceManager.scanLoginDappWithDic(mutableDic) { isSuccess in
//                    if isSuccess {
//                        MHAlert.showMessage(KLocalizedString("ScanloginSuccess"))
//                    } else {
//                        MHAlert.showMessage(KLocalizedString("AlertOpearFail"))
//                    }
//                }
            }
        }
    }
    
    func showWebLoginAlertView(str:String) {
        let alertController = UIAlertController(title: "Reminder", message: "Authorize login to \(str)？", preferredStyle: .alert)

        let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action) in
            
        })
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { UIAlertAction in
        })
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        
        self.present(alertController, animated: true, completion: nil)

    }
    
//MARK: Table
    // 表格视图节的数量
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    // 每个节的行数
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return conversations.count
    }

    // 表格视图单元格配置
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeCell
        let info = conversations[indexPath.row]
        
        
        
//        let msg : DMCCMessage = (info.lastMessage != nil)  ?  info.lastMessage : DMCCMessage()
        
        if  info.timestamp > 0 {
            cell.timeLab.text = formatTimeLabel(info.timestamp)
        }
        
        cell.contentView.backgroundColor = info.isTop ? kGrayBG : .clear
        
//        if let msgText = info.lastMessage?.digest {
        if info.newestMessage.count > 0 {
            cell.contentLab.text = info.newestMessage
        }else{
            cell.contentLab.text = " "
        }

//        DMCCCreateGroupNotificationContent
        switch info.type {
        case .Single, .Notify:
            cell.setUserInfo(userInfo: getUserInfo(info)!)
            if info.type == .Notify {
                cell.icon.image = UIImage(named: "gonggaoIcon")
                cell.nickName.text = KLocalizedString("NotifyMessage")
                cell.contentLab.text = info.newestMessage
            }
        case .Group:
            if info.unreadMention > 0 {
                let text = "\(KLocalizedString("session_mention"))\(String(describing: info.newestMessage))"
                let attrStr = NSMutableAttributedString(string: text)
                attrStr.addAttributes([.foregroundColor: UIColor.init(hex: 0xFF0000)],
                                      range: NSRange(location: 0, length: KLocalizedString("session_mention").count))
                cell.contentLab.attributedText = attrStr
            }

            if info.draft.count > 0 {
                let text = "\(KLocalizedString("ChatMessageDraft"))\(String(describing: info.draft))"
                let attrStr = NSMutableAttributedString(string: text)
                attrStr.addAttributes([.foregroundColor: UIColor.init(hex: 0xFF0000)],
                                      range: NSRange(location: 0, length: KLocalizedString("ChatMessageDraft").count - 2))
                cell.contentLab.attributedText = attrStr
            }
            cell.setGroup(group: getGroupInfo(info)!)
        default:
            break
        }
        
        cell.serverNotCount = serverNotCount
        
        if (info.isSilent) {
            cell.silentImg.isHidden = false;
//            cell.redImg.isHidden = !(info.unread > 0);
            cell.redImg.isHidden = true;
            cell.msgRead.isHidden = true
        } else {
            cell.silentImg.isHidden = true;
            cell.redImg.isHidden = true;
            if (info.unread > 0) {
                if (info.unread > 99) {
                    cell.msgRead.text = "99+";
                } else {
                    cell.msgRead.text = "\(info.unread)";
                }
                cell.msgRead.isHidden = false;
            } else {
                cell.msgRead.isHidden = true;
            }
        }
        
//        cell.cellLongBlock = {
//            print("===cellLongBlock====")
//            ws.cellLongBtnClick(indexPath.row)
//        }
        
        return cell
    }



    // 表格视图选择事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let info = conversations[indexPath.row]
        gosnConversation.clearUnread(info.targetId)
        if info.type == .Notify {
            
            navigationController?.pushViewController(NoticeListVC(), animated: true)
        } else {
            navigationController?.pushViewController(ChatVC(conversation: info), animated: true)
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 75
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let deleteAction = UITableViewRowAction(style: .destructive, title: "删除") { (action, indexPath) in
                // 处理删除操作
            self.deleteChat(indexPath.row)
        }
            
        let editAction = UITableViewRowAction(style: .normal, title: "不显示") { (action, indexPath) in
            // 处理编辑操作
            self.clearChat(indexPath.row)
        }
        
        return [deleteAction, editAction]
    }
    
// MARK: - 通知
    func onReceiveMessages(msg: DMCCMessage) {
        // 处理接收到的消息
        self.updateBadgeNumber()
        
        if gosnConversation.getConversationType(msg.target) == .Single ||  //.getType(msg.target) == 0 ||
            gosnConversation.getConversationType(msg.target) == .Group {
            // reloadOldData(msg)
            cancelGetData()
        } else if gosnConversation.getConversationType(msg.target) == .Notify {
            reloadNotice(msg)
        }
    }

    func updateBadgeNumber() {
        // 更新徽章数字
        let count = gosnConversation.getUnread()//.getUnreadCount(withTagId: 0)  
        
        GK_main_async_safe {
            InfoManager.shared.tabbar!.showBadgeMark(count, index: 0)
        }
    }

    // 用户信息更新
    @objc func kUserInfoUpdated() {
        cancelGetData()
    }

    // 会话列表消息
    @objc func conversationListMessages() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [self] in
            cancelGetData()
        }
    }

    // 群信息更新
    @objc func groupInfoUpdated(_ notification: Notification) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [self] in
            cancelGetData()
        }
    }

    // 好友列表更新消息
    func onFriendListUpdatedMessages() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [self] in
            cancelGetData()
        }
    }
    // MARK: - QR Delegate
    func qrScanner(_ controller: UIViewController, didScanQRCodeWithResult result: String) {
        self.codeAction(code: result)
        scanner.dismiss(animated: true)
    }
    
    func qrScanner(_ controller: UIViewController, didFailWithError error: SwiftQRScanner.QRCodeError) {
        
    }
    
    func qrScannerDidCancel(_ controller: UIViewController) {
        
    }
    
    func setup () {

        tableStytle = .plain
//        tableView.frame = CGRect(x: 0, y: GKNavHeight + 10, width: kScreenWidth, height: kScreenHeight - GKNavHeight - 10)
        let head = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(conversationListMessages))
        head.lastUpdatedTimeLabel?.isHidden = true
        head.stateLabel?.isHidden = true
        self.tableView.mj_header = head
        
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 71, bottom: 0, right: 0)
        tableView.register(UINib(nibName: "HomeCell", bundle: nil), forCellReuseIdentifier: "HomeCell")
        
        self.navigationItem.rightBarButtonItem = self.rt_customBackItemWithTarget(self, action: #selector(showPopView), image: "add")
    }
    
    @objc func showPopView () {
        self.addView.show()
    }
    
    deinit {
//        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: OsnEvent.ReceiveMessages.rawValue), object: nil)
        geventService.removeObserver(OsnEvent.ReceiveMessages, "ReceiveMessages_HomeVC")
        geventService.removeObserver(OsnEvent.FriendListUpdated, "FriendListUpdated_HomeVC")
        geventService.removeObserver(OsnEvent.RecallMessages, "RecallMessages_HomeVC")
        geventService.removeObserver(OsnEvent.kUpDateConversation, "kUpDateConversation_HomeVC")
        
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: kUpdateConversation), object: nil)
    }

}

